import React, { useRef, useEffect, useState, useMemo, useCallback } from 'react'
import './index.less'
import { cloneDeep } from 'lodash'
import { throttle, useThrottle } from '../../utils/tool'
import styles from '../form/index.module.less'
import BackHomeBtn from '../../components/backHome'

const initData = []
for (let i = 0; i < 50; i++) {
	initData.push({
		key: i.toString(),
		val: 'Item' + i,
	})
}

/**
 *
 * @param props
 * @last 剩余几个加载下一页数据 初始 2
 * @itemHeight 每一行的高度 初始30
 */

const Index = (props) => {
	const { last = 2, itemHeight = 30 } = props
	const virtualListRef = useRef()
	const [totalHeight, setTotalHeight] = useState('') // 虚拟盒子的总高度
	const [transform, setTransform] = useState('') // 实际盒子需要移动的距离
	const [data, setData] = useState([]) // 实际显示的数据
	const [totalData, setTotalData] = useState(initData) // 总数据
	const [scrollTop, setScrollTop] = useState(0) // 滚动高度
	const throttleScrollTop = useThrottle(scrollTop, 200)

	const getData = () => {
		// 拼接数据
		const start = totalData.length
		const targetData = [...totalData]
		new Array(20).fill(1).forEach((i, t) => {
			const num = start + t
			targetData.push({
				key: num.toString(),
				val: 'Item' + num,
			})
		})
		setTotalData(targetData)
	}

	const updateViewContent = (scrollTop = 0) => {
		const totalEnd = totalData.length
		// 计算可视区域里能放几个元素
		const viewCount = Math.ceil(virtualListRef.current.clientHeight / itemHeight)
		// 计算可视区域开始的索引
		const start = Math.floor(scrollTop / itemHeight)
		// 计算可视区域结束索引
		const end = start + viewCount
		if (end >= totalEnd - last) {
			// 根据最后的索引与总的数据长度进行比较 请求下一页数据
			getData()
		}
		// 截取可视区域数据
		const viewData = totalData.slice(start, end)
		setData(viewData)
		setTransform(`translateY(${start * itemHeight}px)`)
	}

	useEffect(() => {
		const totalH = totalData.length * itemHeight + 'px'
		setTotalHeight(totalH)
	}, [totalData, itemHeight])

	useEffect(() => {
		updateViewContent()
	}, [])

	/*
	 * 获取scrollTop
	 * 此属性可以获取或者设置对象的最顶部到对象在当前窗口显示的范围内的顶边的距离
	 * 也就是元素滚动条被向下拉动的距离
	 * */
	const handleScroll = (e) => {
		setScrollTop(e.target.scrollTop)
	}

	useEffect(() => {
		updateViewContent(throttleScrollTop)
	}, [throttleScrollTop])

	return (
		<div>
			<div className={styles.btnBox}>
				<BackHomeBtn />
			</div>
			<div className="virtual-list" onScroll={handleScroll} ref={virtualListRef}>
				<div className="virtual-list-height" style={{ height: totalHeight }} />
				<div className="view-content" style={{ transform: transform }}>
					{data.map(({ key, val }) => {
						return (
							<div className="view-item" key={key}>
								{val}
							</div>
						)
					})}
				</div>
			</div>
			<div>
				<br />
				<br />
				虚拟列表 动态请求数据更新列表 滚动到底部 根据设置的值可以选择剩余几个的时候请求下一页数据 也可以使用节流功能
			</div>
		</div>
	)
}

export default Index
